package com.chinawayltd.ews.sample.web.common;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.chinawayltd.ews.sample.model.TTemplateEvent;
import com.chinawayltd.ews.sample.model.common.CommonVO;
import com.chinawayltd.ews.sample.model.common.MaterielCommonVO;
import com.chinawayltd.ews.sample.service.common.CommonService;
import com.chinawayltd.ews.sample.util.ResultModel;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * @program: greeProject
 * @description
 * @author: chenxin
 * @create: 2018年4月12日 下午8:09:21
 */
@Api(tags = { "共用查询API" })
@RestController
@RequestMapping(value = "/web/common")
public class CommonController {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private CommonService commonService;

	@ApiOperation(value = "通用车辆查询查询接口")
	@RequestMapping(value = "/loadVehicleData", method = { RequestMethod.POST })
	@ApiImplicitParams({
			@ApiImplicitParam(name = "vehicleCode", value = "车牌号", paramType = "query", dataType = "string"),
			@ApiImplicitParam(name = "vehicleId", value = "车辆id", paramType = "query", dataType = "long") })
	public ResultModel loadVehicleData(String vehicleCode, Long vehicleId) {
		ResultModel model = new ResultModel();
		try {
			List<CommonVO> dataList = commonService.listVehicleData(vehicleCode, vehicleId);
			model.setCode(0);
			model.setSub_code(0);
			model.setData(new JSONObject().fluentPut("result", dataList));
		} catch (Exception e) {
			logger.error("通用车辆查询查询出错！", e);
		}
		return model;
	}

	@ApiOperation(value = "通用司机查询查询接口")
	@RequestMapping(value = "/loadDriverData", method = { RequestMethod.POST })
	@ApiImplicitParams({
			@ApiImplicitParam(name = "driverName", value = "司机名称", paramType = "query", dataType = "string"),
			@ApiImplicitParam(name = "driverId", value = "司机id", paramType = "query", dataType = "long") })
	public ResultModel loadDriverData(String driverName, Long driverId) {
		ResultModel model = new ResultModel();
		try {
			List<CommonVO> dataList = commonService.listDriverData(driverName, driverId);
			model.setCode(0);
			model.setSub_code(0);
			model.setData(new JSONObject().fluentPut("result", dataList));
		} catch (Exception e) {
			logger.error("通用司机查询查询出错！", e);
		}
		return model;
	}

	@ApiOperation(value = "通用班次查询查询接口")
	@RequestMapping(value = "/loadShiftData", method = { RequestMethod.POST })
	@ApiImplicitParams({
			@ApiImplicitParam(name = "shiftName", value = "班次名称", paramType = "query", dataType = "string"),
			@ApiImplicitParam(name = "shiftId", value = "班次id", paramType = "query", dataType = "long") })
	public ResultModel loadShiftData(String shiftName, Long shiftId) {
		ResultModel model = new ResultModel();
		try {
			List<CommonVO> dataList = commonService.listShiftData(shiftName, shiftId);
			model.setCode(0);
			model.setSub_code(0);
			model.setData(new JSONObject().fluentPut("result", dataList));
		} catch (Exception e) {
			logger.error("通用班次查询查询出错！", e);
		}
		return model;
	}

	@ApiOperation(value = "通用物料查询接口")
	@RequestMapping(value = "/loadMaterielData", method = { RequestMethod.POST })
	@ApiImplicitParams({
			@ApiImplicitParam(name = "materielName", value = "物料名称", paramType = "query", dataType = "string"),
			@ApiImplicitParam(name = "materielId", value = "物料id", paramType = "query", dataType = "long") })
	public ResultModel loadMaterielData(String materielName, Long materielId) {
		ResultModel model = new ResultModel();
		try {
			List<MaterielCommonVO> dataList = commonService.listMaterielData(materielName, materielId);
			model.setCode(0);
			model.setSub_code(0);
			model.setData(new JSONObject().fluentPut("result", dataList));
		} catch (Exception e) {
			logger.error("通用物料查询出错！", e);
		}
		return model;
	}

	@ApiOperation(value = "通用站点查询查询接口", notes="orderNo-订单号</br>startPlace-取货站点id</br>")
	@RequestMapping(value = "/loadBranchData", method = { RequestMethod.POST })
	@ApiImplicitParams({
			@ApiImplicitParam(name = "branchName", value = "站点名称", paramType = "query", dataType = "string"),
			@ApiImplicitParam(name = "branchFromType", value = "站点所属类型", paramType = "query", dataType = "string"),
			@ApiImplicitParam(name = "branchId", value = "站点id", paramType = "query", dataType = "long") })
	public ResultModel loadBranchData(String branchName, String branchFromType, Long branchId) {
		ResultModel model = new ResultModel();
		try {
			List<CommonVO> dataList = commonService.loadBranchData(branchName, branchFromType, branchId);
			model.setCode(0);
			model.setSub_code(0);
			model.setData(new JSONObject().fluentPut("result", dataList));
		} catch (Exception e) {
			logger.error("通用班次查询查询出错！", e);
		}
		return model;
	}

	
	@ApiOperation(value = "查询字典项接口", notes="typeCode的取值有：<br/>"
			+ "订单生成状态:order_generate_status,<br/>"
			+ "订单执行状态:order_execute_status,<br/>"
			+ "订单产生来源:order_entry_source,<br/>"
			+ "任务确认状态:task_confirm_status,<br/>"
			+ "任务执行状态:task_execute_status,<br/>"
			+ "节点类型:node_type'"
			+ "节点执行状态:node_execute_status,<br/>"
			+ "后续还会新增新的字典类型！！")
	@RequestMapping(value = "/listDictData", method = { RequestMethod.POST })
	@ApiImplicitParams({
			@ApiImplicitParam(name = "typeCode", value = "字典项类型", paramType = "query", dataType = "string", required = true),
			@ApiImplicitParam(name = "infoName", value = "字典项名称", paramType = "query", dataType = "string"),
			@ApiImplicitParam(name = "infoValue", value = "字典项值", paramType = "query", dataType = "string")})
	public ResultModel listDictData(String typeCode, String infoName, String infoValue) {
		ResultModel model = new ResultModel();
		try {
			List<CommonVO> dataList = commonService.listDictData(typeCode, infoName, infoValue);
			model.setCode(0);
			model.setSub_code(0);
			model.setData(new JSONObject().fluentPut("result", dataList));
		} catch (Exception e) {
			logger.error("查询字典项出错！", e);
		}
		return model;
	}
	
	/*@ApiOperation(value = "下载导入Excel模板接口", notes = "0-物料订单，1-物料基础信息，2-站点信息，3-站点耗时，4-道路限行，5-班次信息，6-司机排班")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "type", value = "模板类型", paramType = "query", dataType = "int", required = true) })
	@RequestMapping(value = "/downloadExcelModel", method = { RequestMethod.GET })
	public String download(HttpServletRequest request, int type, HttpServletResponse response) {
		OutputStream os = null;
		InputStream inputStream = null;
		try {
			String[] fileNames = new String[] { "OrderModel", "MaterielModel", "BranchModel", "BranchConsumeTimeModel", "LimiterModel", "DriverPlanModel", "DriverPlanModel" };
			String[] model = new String[] { "物料订单导入模板", "物料基础导入模板", "站点信息导入模板", "站点耗时导入模板", "道路限行导入模板", "班次导入模板", "司机排班导入模板" };
			String fileName = model[type];
			String fileName_ = fileNames[type];
			
			String file = this.getClass().getClassLoader().getResource("static/downloadModel/" + fileName_ + ".xlsx").getFile();
			logger.info("------------------------------------------------");
			logger.info("路径", this.getClass().getClassLoader());
			logger.info(file);
			logger.info("------------------------------------------------");
			
			response.setContentType("application/xlsx");
			response.setCharacterEncoding("UTF-8");
			String agent = request.getHeader("User-Agent");
			boolean isMSIE = (agent != null && agent.indexOf("MSIE") != -1);
			if (isMSIE) {
				fileName = URLEncoder.encode(fileName, "UTF8");
			} else {
				fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
			}
			response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx");
			inputStream = new FileInputStream(new File(file));

			os = response.getOutputStream();
			int length;
			while ((length = inputStream.read()) != -1) {
				os.write(length);
			}

			
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("导出文件downloadExcelModel接口异常",e);
		} finally {
			// 这里主要关闭。
			try {
				if(os != null){
					os.close();
				}
				if(inputStream != null){
					inputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}*/

	
    @ApiOperation(value = "查询异常类型接口")
	@RequestMapping(value = "/loadEventListData", method = { RequestMethod.POST })
	@ApiImplicitParams({
			@ApiImplicitParam(name = "eventName", value = "异常名称", paramType = "query", dataType = "string"),
			@ApiImplicitParam(name = "eventId", value = "异常id", paramType = "query", dataType = "long") })
	public ResultModel loadEventListData(String eventName, Long eventId) {
		ResultModel model = new ResultModel();
		try {
			List<TTemplateEvent> dataList = commonService.loadEventListData(eventName, eventId);
			model.setCode(0);
			model.setSub_code(0);
			model.setData(new JSONObject().fluentPut("result", dataList));
		} catch (Exception e) {
			logger.error("通用班次查询查询出错！", e);
		}
		return model;
	}
    
	/*
	 * @ApiOperation(value = "通过表名和数据ID查询操作日记接口")
	 * 
	 * @RequestMapping(value = "/getLogDataById", method = { RequestMethod.POST
	 * })
	 * 
	 * @ApiImplicitParams({
	 * 
	 * @ApiImplicitParam(paramType = "query", name = "tableName", value =
	 * "数据库表名称", dataType = "String", required = true),
	 * 
	 * @ApiImplicitParam(paramType = "query", name = "dataId",value =
	 * "数据的id，主键",dataType = "Long", required = true) }) public ResultModel
	 * getLogDataById(String tableName, Long dataId) { ResultModel model = new
	 * ResultModel(); try { if(dataId == null || dataId <= 0){ throw new
	 * RuntimeException("id不能为空或者少于等于0！"); } List<TLog> list =
	 * commonService.getLogDataById(dataId, tableName); model.setCode(0);
	 * model.setSub_code(0); model.setData(new JSONObject().fluentPut("result",
	 * list)); }catch (Exception e){ logger.error("通过表名和数据ID查询操作日记接口！", e); }
	 * return model; }
	 */

	/*
	 * @ApiOperation(value = "通过表名和数据ID新增操作日记接口")
	 * 
	 * @RequestMapping(value = "/addLog", method = { RequestMethod.POST })
	 * 
	 * @ApiImplicitParams({
	 * 
	 * @ApiImplicitParam(paramType = "query", name = "tableName", value =
	 * "数据库表名称", dataType = "String", required = true),
	 * 
	 * @ApiImplicitParam(paramType = "query", name = "dataId",value =
	 * "数据的id，主键",dataType = "Long", required = true) }) public ResultModel
	 * addLog(String tableName, Long dataId) { ResultModel model = null; try {
	 * int result = commonService.addLog(dataId, tableName,0); if(result > 0)
	 * model = new ResultModel(0, 0, new JSONObject().fluentPut("result" ,
	 * "添加成功")); else model = new ResultModel(0, 0, new
	 * JSONObject().fluentPut("sub_msg" , "添加失败")); } catch (Exception e) {
	 * e.printStackTrace(); logger.error("通过表名和数据ID新增操作日记发生异常！", e); } return
	 * model; }
	 */

}
